<?php
header('Content-Type: application/json');
Header('Access-Control-Allow-Methods:GET,POST,PUT,DELETE');
header("Access-Control-Allow-Headers: Content-Type");
header('Access-Control-Allow-Origin:*');   //跨域

require './mysql_init.php';

//检查数据是否正常
function limit_up_data($session_id){
    $flag=1;
    if(gettype($session_id) != 'string'){
        $flag=0;
    }
    if(strlen($session_id) < 2 || strlen($session_id) > 300){
        $flag=0;
    }
    return $flag;
}
//获取邮箱
function get_email($pdo,$session_id){
    try {
        // 准备查询语句
        $query = "SELECT email FROM session WHERE session_id = ?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $session_id);
        // 执行查询
        $statement->execute();
        // 获取结果
        $result = $statement->fetchAll()[0]['email'];      //把查询结构赋值给$count
        return $result;
    } catch (PDOException $e) {
        // 异常处理
        // echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}
//获取uid
function get_uid($pdo,$email){
    try {
        // 准备查询语句
        $query = "SELECT uid FROM users WHERE email = ?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $email);
        // 执行查询
        $statement->execute();
        // 获取结果
        $result = $statement->fetchAll()[0]['uid'];      //把查询结构赋值给$count
        return $result;
    } catch (PDOException $e) {
        // 异常处理
        // echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}

//通过goods_id获取商家id
function get_sellerid($pdo,$goods_id){
    try {
        // 准备查询语句
        $query = "SELECT seller_id  FROM goods WHERE goods_id =?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $goods_id);
        // 执行查询
        $statement->execute();
        // 获取结果
        $result = $statement->fetchAll()[0]['seller_id'];      //把查询结构赋值给$count
        return $result;
    } catch (PDOException $e) {
        // 异常处理
        // echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}
//获取默认地址的id
function get_default_address_id($pdo,$uid){
    try {
        // 准备查询语句
        $query = "SELECT address_id FROM shipping_address WHERE user_uid=? and is_forbidden=0 and is_default_address=1";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $uid);
        // 执行查询
        $statement->execute();
        // 获取结果
        $result = $statement->fetchAll()[0]['address_id'];      //把查询结构赋值给$count

        $query2 = "SELECT count(*) FROM shipping_address WHERE user_uid=? and is_forbidden=0 and is_default_address=1";
        $statement2 = $pdo->prepare($query2);
        $statement2->bindParam(1, $uid);
        // 执行查询
        $statement2->execute();
        $result2 = $statement2->fetchAll()[0]['count(*)'];      //把查询结构赋值给$count

        if($result2==1){
            return $result;
        }else{
            return -2;
        }
    } catch (PDOException $e) {
        // 异常处理
        // echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}
//判断商品的数量和价格是否变动
function limit_is_goods_news_change($pdo,$goods_id,$goods_count,$goods_price){
    try {
        // 准备查询语句
        $query = "SELECT count(*) FROM goods WHERE goods_id=? and ROUND(price,2)=? and count>=?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $goods_id);
        $statement->bindParam(2, $goods_price);
        $statement->bindParam(3, $goods_count);
        // 执行查询
        $statement->execute();
        // 获取结果
        $response = $statement->fetchAll()[0]['count(*)'];      //把查询结构赋值给$count
        if($response==1){
            return 1;
        }else{
            return 0;
        }
    } catch (PDOException $e) {
        // 异常处理
        // echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}
//锁定价格，数量，生成订单
function lock_goods_count_and_create_orders($pdo,$goods_id,$uid,$goods_count,$address_id,$goods_price,$seller_id){
    try {
        $pdo -> setAttribute(PDO::ATTR_AUTOCOMMIT,0);     //事务是否自动提交，0是关闭，1是自动
        $pdo -> beginTransaction();        //开启事务

        // 准备插入语句
        $query = "INSERT INTO orders(goods_id, user_uid, address_id, count, order_price,seller_id) VALUES(?,?,?,?,?,?)";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $goods_id);
        $statement->bindParam(2, $uid);
        $statement->bindParam(3, $address_id);
        $statement->bindParam(4, $goods_count);
        $statement->bindParam(5, $goods_price);
        $statement->bindParam(6, $seller_id);
        // 执行查询
        $statement->execute();
        // 获取结果
        $result = $statement->rowCount();      //受影响行数

        $query2 ="UPDATE goods SET count=count-? WHERE goods_id=?";
        $statement2 = $pdo->prepare($query2);
        $statement2->bindParam(1, $goods_count);
        $statement2->bindParam(2, $goods_id);
        // 执行查询
        $statement2->execute();
        // 获取结果
        $result2 = $statement2->rowCount();      //把查询结构赋值给$count

        if($result==1 && $result2==1){
            $pdo -> commit();
            $pdo -> setAttribute(PDO::ATTR_AUTOCOMMIT,1);     //事务是否自动提交，0是关闭，1是自动
            return 1;
        }else{
            $pdo -> rollback();
            $pdo -> setAttribute(PDO::ATTR_AUTOCOMMIT,1);     //事务是否自动提交，0是关闭，1是自动
            return 0;
        }
    } catch (PDOException $e) {
        // 异常处理
        // echo "Error querying database: " . $e->getMessage();
        $pdo -> rollback();
        $pdo -> setAttribute(PDO::ATTR_AUTOCOMMIT,1);     //事务是否自动提交，0是关闭，1是自动
        return -1; // 表示查询出错
    }
}
//获取刚生成的订单的id
function get_order_id($pdo,$uid){
    try {
        // 准备查询语句
        $query = "SELECT max(order_id) FROM orders WHERE user_uid=?;";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $uid);
        // 执行查询
        $statement->execute();
        // 获取结果
        $result = $statement->fetchAll()[0]['max(order_id)'];      //把查询结构赋值给$count
        return $result;
    } catch (PDOException $e) {
        // 异常处理
        // echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}



if($_SERVER['REQUEST_METHOD'] === 'POST'){
    $json=file_get_contents('php://input');  //获取post请求中的原始数据
    $post_json=json_decode($json,true);       //把原始数据转化成json

    $session_id=$post_json['session_id'];
    $goods_id=$post_json['goods_id'];
    $goods_price=$post_json['goods_prace'];
    $goods_count=$post_json['count'];
    
    $response = array(
        'status' => 0,
        'message' =>'初始化'
    );
    if(limit_up_data($session_id)==1){      //验证上传的session_id数据类型是否合法
        if(gettype(get_email($pdo,$session_id))=='string'){
            $email=get_email($pdo,$session_id);
            $uid=get_uid($pdo,$email);

            if(limit_is_goods_news_change($pdo,$goods_id,$goods_count,$goods_price) ==1){
                $address_id=get_default_address_id($pdo,$uid);
                if($address_id==-2){
                    $response = array(
                        'status' => 0,
                        'message' => '没有设置默认收货地址'
                    );
                }elseif($address_id==-1){
                    $response = array(
                        'status' => 0,
                        'message' => '异常，请上报错误'
                    );
                }else{
                    $seller_id=get_sellerid($pdo,$goods_id);
                    $n=lock_goods_count_and_create_orders($pdo,$goods_id,$uid,$goods_count,$address_id,$goods_price,$seller_id);
                    if($n == 1){
                        $order_id=get_order_id($pdo,$uid);
                        $response = array(
                            'status' => 1,
                            'message' => '创建订单成功,10分钟后过期',
                            'order_id' => $order_id
                        );
                    }else{
                        $response = array(
                            'status' => 0,
                            'message' => '出错了，请重试'
                        );
                    }
                }  
            }else{
                $response = array(
                    'status' => 0,
                    'message' => '价格变动或数量不足，请重新刷新'
                );
            }
        }else{
            $response = array(
                'status' => 0,
                'message' => '用户不存在或未登录'
            );
        }
    }else{
        $response = array(
            'status' => 0,
            'message' => '数据类型错误'
        );
    }

    echo json_encode($response);
} else{             //如果不是post请求
    $response = array(
        'status' => 0,
        'message' => '不是请求'
    );
    echo json_encode($response);
}
?>